from django.forms.models import ModelForm
from django.forms.util import ValidationError
from django.contrib import admin
from best_buy_book.shop.models import *
from django.contrib.auth.models import User

class UserInline(admin.StackedInline):
    model = User
    extra = 1

class PersonaInline(admin.StackedInline):
    model = Persona

class KeywordAdmin(admin.ModelAdmin):
    pass

class PersonaAdmin(admin.ModelAdmin):
    fieldsets = ( (None, {
        'fields': ('username', 'first_name', 'last_name')
    }),)
    pass

class AutorAdminForm(ModelForm):
    inlines = [
        PersonaInline,
    ]
    class Meta:
        model = Autor    
    def clean_biografia(self):
        data = self.cleaned_data['biografia']
        total = len(data.split())
        if total > 150:
            total -= 150
            raise ValidationError("El maximo de palabras es 150, te excediste por %s palabras" % total)
        return data

class AutorAdmin(admin.ModelAdmin):
    form = AutorAdminForm
    fieldsets = ( (None, {
        'fields': (
            'username', 'first_name', 'last_name', 'fecha_nacimiento',
            'defuncion', 'pais', 'biografia'
        )
    }),)
    pass

class LibroAdminForm(ModelForm):
    def clean_keyword(self):
        data = self.cleaned_data['keyword']
        isbn = self.cleaned_data['isbn']
        total = len(data)
        total_isbn = len(isbn)
        if total > 10:
            total -= 10
            raise ValidationError("El maximo de palabras clave es 10, te excediste por %s palabras" % total)
        if total_isbn != 10:
            raise ValidationError("El ISBN se compone de 10 caracteres")
        return data

    
class LibroAdmin(admin.ModelAdmin):
    form = LibroAdminForm
    filter_horizontal = ('autor', 'keyword')
    pass

class ClienteAdmin(admin.ModelAdmin):
    fieldsets = ( (None, {
        'fields': (
            'username', 'first_name', 'last_name', 'email', 'direccion',
            'codigo_postal', 'ciudad', 'estado', 'telefono', 'password',
            'tarjeta_tipo', 'tarjeta_numero', 'tarjeta_fecha_exp', 'is_active'
        )
    }),)
    pass

admin.site.register(Keyword, KeywordAdmin)
admin.site.register(Autor, AutorAdmin)
admin.site.register(Libro, LibroAdmin)
admin.site.register(Cliente, ClienteAdmin)